﻿using System;
using System.Net;
using SharpSvn;

namespace SvnDeploy.Service.Impl
{
    internal class SvnAdapterImpl : ISvnAdapter
    {
        private readonly SvnClient svnClient;

        public SvnAdapterImpl()
        {
            svnClient = new SvnClient();
            WasUpdated = false;
        }

        public long Revision { get; private set; }

        public bool WasUpdated { get; private set; }

        public void Dispose()
        {
            if (svnClient != null)
            {
                svnClient.Dispose();
            }
        }

        public void CheckOut(Uri uri, string path)
        {
            SvnUpdateResult result;
            svnClient.CheckOut(uri, path, out result);
            WasUpdated = true;
            Revision = result.Revision;
        }

        public void SetAuthentication(ICredentials credentials)
        {
            svnClient.Authentication.Clear();
            svnClient.Authentication.DefaultCredentials = credentials;
        }

        public void Update(string path)
        {
            SvnInfoEventArgs infoArgs;
            svnClient.GetInfo(path, out infoArgs);
            SvnUpdateResult updateResult;
            svnClient.Update(path, out updateResult);
            WasUpdated = infoArgs.Revision != updateResult.Revision;
            Revision = updateResult.Revision;
        }
    }
}
